import 'package:flutter/material.dart';

class CustomCarouselIndicator extends StatefulWidget {
  final int itemCount;
  final int currentIndex;
  final int maxVisibleItems;
  final IndexedWidgetBuilder itemBuilder;
  final double itemSpacing;
  final double itemHeight;
  final ValueChanged<int>? onItemTap;

  const CustomCarouselIndicator({
    Key? key,
    required this.itemCount,
    required this.currentIndex,
    required this.itemBuilder,
    this.maxVisibleItems = 5,
    this.itemSpacing = 8,
    this.itemHeight = 60,
    this.onItemTap,
  }) : super(key: key);

  @override
  State<CustomCarouselIndicator> createState() => _CustomCarouselIndicatorState();
}

class _CustomCarouselIndicatorState extends State<CustomCarouselIndicator> {
  final ScrollController _scrollController = ScrollController();

  @override
  void didUpdateWidget(covariant CustomCarouselIndicator oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.currentIndex != widget.currentIndex) {
      _scrollToCurrentIndex();
    }
  }

  void _scrollToCurrentIndex() {
    final totalHeight = widget.itemCount * (widget.itemHeight + widget.itemSpacing);
    final maxScrollExtent = totalHeight -
        widget.maxVisibleItems * (widget.itemHeight + widget.itemSpacing);

    double targetOffset = (widget.itemHeight + widget.itemSpacing) *
        (widget.currentIndex - (widget.maxVisibleItems ~/ 2));

    targetOffset = targetOffset.clamp(0.0, maxScrollExtent.toDouble());

    _scrollController.animateTo(
      targetOffset,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final visibleCount = widget.itemCount < widget.maxVisibleItems
        ? widget.itemCount
        : widget.maxVisibleItems;

    return SizedBox(
      height: visibleCount * widget.itemHeight + (visibleCount - 1) * widget.itemSpacing,
      width: widget.itemHeight, // 默认正方形 item
      child: ListView.separated(
        controller: _scrollController,
        itemCount: widget.itemCount,
        separatorBuilder: (_, __) => SizedBox(height: widget.itemSpacing),
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              if (widget.onItemTap != null) {
                widget.onItemTap!(index);
              }
            },
            child: widget.itemBuilder(context, index),
          );
        },
      ),
    );
  }
}
